package thoven.achievement.net.ideapluginachievement.ui

import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBTabbedPane
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.JBUI
import thoven.achievement.net.ideapluginachievement.model.Achievement
import thoven.achievement.net.ideapluginachievement.model.AchievementType
import thoven.achievement.net.ideapluginachievement.model.CodeStats
import thoven.achievement.net.ideapluginachievement.service.CodeStatsService
import thoven.achievement.net.ideapluginachievement.service.RecommendationService
import thoven.achievement.net.ideapluginachievement.service.ExportService
import thoven.achievement.net.ideapluginachievement.service.SettingsService
import thoven.achievement.net.ideapluginachievement.service.ReportType
import thoven.achievement.net.ideapluginachievement.ui.ReportDialog
import javax.swing.JButton
import java.awt.*
import javax.swing.*
import javax.swing.border.EmptyBorder
import javax.swing.table.DefaultTableModel
import javax.swing.table.DefaultTableCellRenderer

/**
 * 代码统计对话框
 */
class CodeStatsDialog(private val project: Project) : DialogWrapper(project) {

    private val LOG = logger<CodeStatsDialog>()
    private val recommendationService = RecommendationService.getInstance(project)
    private val exportService = ExportService.getInstance(project)
    private val settingsService = SettingsService.getInstance()
    
    init {
        title = "代码统计"
        init()
    }
    
    override fun createCenterPanel(): JComponent {
        val panel = JPanel(BorderLayout())
        panel.preferredSize = Dimension(750, 600)
        panel.border = JBUI.Borders.empty(0)
        
        val tabbedPane = JBTabbedPane()
        
        // 今日统计标签页
        tabbedPane.add("今日统计", createTodayStatsPanel())
        
        // 智能推荐标签页
        tabbedPane.add("智能推荐", createRecommendationPanel())
        
        // 成就标签页
        tabbedPane.add("成就", createAchievementsPanel())
        
        // 导出分享标签页
        tabbedPane.add("导出分享", createExportPanel())
        
        panel.add(tabbedPane, BorderLayout.CENTER)
        
        return panel
    }
    
    override fun createSouthPanel(): JComponent? {
        // 不显示底部按钮
        return null
    }
    
    /**
     * 创建今日统计面板
     */
    private fun createTodayStatsPanel(): JComponent {
        val panel = JPanel(BorderLayout(0, 20))
        panel.border = JBUI.Borders.empty(20)
        panel.background = JBColor(Color(43, 43, 43), Color(43, 43, 43))
        
        val codeStatsService = CodeStatsService.getInstance(project)
        val aggregatedStats = codeStatsService.getAggregatedStats()
        val todayStats = codeStatsService.getTodayStats()
        val consecutiveDays = codeStatsService.getConsecutiveDays()
        
        // 创建主容器
        val mainPanel = JPanel()
        mainPanel.layout = BoxLayout(mainPanel, BoxLayout.Y_AXIS)
        mainPanel.background = panel.background
        
        // 顶部标题面板
        val titlePanel = JPanel(FlowLayout(FlowLayout.CENTER, 10, 0))
        titlePanel.background = panel.background
        val iconLabel = JBLabel("📊")
        iconLabel.font = iconLabel.font.deriveFont(24f)
        val titleLabel = JBLabel("今日代码统计")
        titleLabel.font = titleLabel.font.deriveFont(Font.BOLD, 22f)
        titleLabel.foreground = Color.WHITE
        titlePanel.add(iconLabel)
        titlePanel.add(titleLabel)
        mainPanel.add(titlePanel)
        mainPanel.add(Box.createVerticalStrut(20))
        
        // 创建数据卡片面板
        val cardsPanel = JPanel(GridLayout(1, 3, 15, 0))
        cardsPanel.background = panel.background
        cardsPanel.maximumSize = Dimension(Int.MAX_VALUE, 150)
        
        // 今日新增卡片（绿色渐变）
        val addedCard = createModernStatCard(
            "今日新增行数",
            aggregatedStats.todayAdded.toString(),
            "✓",
            Color(76, 175, 80),
            Color(129, 199, 132)
        )
        cardsPanel.add(addedCard)
        
        // 今日删除卡片（红橙色渐变）
        val deletedCard = createModernStatCard(
            "今日删除行数",
            aggregatedStats.todayDeleted.toString(),
            "×",
            Color(244, 67, 54),
            Color(255, 152, 0)
        )
        cardsPanel.add(deletedCard)
        
        // 净增行数卡片（蓝色渐变）
        val totalCard = createModernStatCard(
            "累计净行数",
            aggregatedStats.totalNet.toString(),
            "📈",
            Color(33, 150, 243),
            Color(100, 181, 246)
        )
        cardsPanel.add(totalCard)
        
        mainPanel.add(cardsPanel)
        mainPanel.add(Box.createVerticalStrut(30))
        
        // 创建按语言统计面板
        val languagePanel = JPanel(BorderLayout(0, 15))
        languagePanel.background = panel.background
        languagePanel.maximumSize = Dimension(Int.MAX_VALUE, 200)
        
        // 标题
        val languageTitlePanel = JPanel(FlowLayout(FlowLayout.LEFT, 10, 0))
        languageTitlePanel.background = panel.background
        val globeIcon = JBLabel("🌐")
        globeIcon.font = globeIcon.font.deriveFont(18f)
        val languageTitle = JBLabel("按语言统计")
        languageTitle.font = languageTitle.font.deriveFont(Font.BOLD, 18f)
        languageTitle.foreground = Color.WHITE
        languageTitlePanel.add(globeIcon)
        languageTitlePanel.add(languageTitle)
        languagePanel.add(languageTitlePanel, BorderLayout.NORTH)
        
        // 创建不可编辑的表格
        val tableModel = object : DefaultTableModel() {
            override fun isCellEditable(row: Int, column: Int): Boolean {
                return false
            }
        }
        tableModel.addColumn("语言")
        tableModel.addColumn("新增")
        tableModel.addColumn("删除")
        tableModel.addColumn("净行")
        
        // 如果没有统计数据，添加空行
        if (todayStats.isEmpty()) {
            tableModel.addRow(arrayOf("暂无数据", "-", "-", "-"))
        } else {
        for (stat in todayStats) {
            tableModel.addRow(arrayOf(
                stat.language,
                stat.addedLines,
                stat.deletedLines,
                stat.netLines
            ))
            }
        }
        
        val table = JBTable(tableModel)
        table.setShowGrid(false)
        table.rowHeight = 35
        table.background = JBColor(Color(55, 55, 55), Color(55, 55, 55))
        table.foreground = Color.WHITE
        table.font = table.font.deriveFont(14f)
        table.tableHeader.background = JBColor(Color(50, 50, 50), Color(50, 50, 50))
        table.tableHeader.foreground = Color.WHITE
        table.tableHeader.font = table.tableHeader.font.deriveFont(Font.BOLD, 13f)
        table.tableHeader.border = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        
        // 居中对齐
        val centerRenderer = DefaultTableCellRenderer()
        centerRenderer.horizontalAlignment = SwingConstants.CENTER
        centerRenderer.background = table.background
        centerRenderer.foreground = table.foreground
        for (i in 0 until table.columnCount) {
            table.columnModel.getColumn(i).cellRenderer = centerRenderer
        }
        
        val scrollPane = JBScrollPane(table)
        scrollPane.border = BorderFactory.createLineBorder(JBColor(Color(70, 70, 70), Color(70, 70, 70)), 1)
        scrollPane.preferredSize = Dimension(Int.MAX_VALUE, 120)
        languagePanel.add(scrollPane, BorderLayout.CENTER)
        
        mainPanel.add(languagePanel)
        mainPanel.add(Box.createVerticalStrut(25))
        
        // 报告按钮面板
        val reportButtonsPanel = JPanel(FlowLayout(FlowLayout.CENTER, 15, 0))
        reportButtonsPanel.background = panel.background
        reportButtonsPanel.maximumSize = Dimension(Int.MAX_VALUE, 50)
        
        reportButtonsPanel.add(createReportButton("📊 生成日报", ReportType.DAILY))
        reportButtonsPanel.add(createReportButton("📈 生成周报", ReportType.WEEKLY))
        reportButtonsPanel.add(createReportButton("📅 生成月报", ReportType.MONTHLY))
        
        mainPanel.add(reportButtonsPanel)
        mainPanel.add(Box.createVerticalStrut(20))
        
        // 底部总结文字
        val summaryText = generateSummaryText(aggregatedStats.todayAdded, todayStats)
        val summaryLabel = JBLabel(summaryText)
        summaryLabel.font = summaryLabel.font.deriveFont(Font.ITALIC, 14f)
        summaryLabel.foreground = JBColor(Color(180, 180, 180), Color(180, 180, 180))
        summaryLabel.horizontalAlignment = SwingConstants.CENTER
        summaryLabel.alignmentX = Component.CENTER_ALIGNMENT
        mainPanel.add(summaryLabel)
        
        panel.add(mainPanel, BorderLayout.CENTER)
        
        return panel
    }
    
    /**
     * 创建成就面板（专业级设计）
     */
    private fun createAchievementsPanel(): JComponent {
        val mainPanel = JPanel(BorderLayout())
        mainPanel.background = JBColor(Color(30, 30, 30), Color(30, 30, 30))
        
        val codeStatsService = CodeStatsService.getInstance(project)
        val unlockedAchievements = codeStatsService.getUnlockedAchievements()
        val todayAchievements = codeStatsService.getTodayAchievements()
        
        // 创建顶部统计栏
        val statsBar = createAchievementStatsBar(unlockedAchievements, todayAchievements)
        mainPanel.add(statsBar, BorderLayout.NORTH)
        
        // 创建主内容区域
        val contentPanel = JPanel(BorderLayout(0, 0))
        contentPanel.background = mainPanel.background
        contentPanel.border = JBUI.Borders.empty(15, 20, 20, 20)
        
        // 如果有今日成就，创建今日成就区域
        if (todayAchievements.isNotEmpty()) {
            val todaySection = createTodayAchievementsSection(todayAchievements)
            contentPanel.add(todaySection, BorderLayout.NORTH)
        }
        
        // 创建所有成就网格
        val allAchievementsPanel = createAllAchievementsGrid(unlockedAchievements)
        contentPanel.add(allAchievementsPanel, BorderLayout.CENTER)
        
        mainPanel.add(contentPanel, BorderLayout.CENTER)
        
        return mainPanel
    }
    
    /**
     * 创建成就统计栏
     */
    private fun createAchievementStatsBar(unlockedAchievements: List<Achievement>, todayAchievements: List<Achievement>): JComponent {
        val totalAchievements = AchievementType.values().size
        val unlockedCount = unlockedAchievements.size
        val percentage = if (totalAchievements > 0) (unlockedCount * 100) / totalAchievements else 0
        
        val statsPanel = object : JPanel(BorderLayout()) {
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 渐变背景
                val gradient = GradientPaint(
                    0f, 0f, Color(45, 45, 45),
                    0f, height.toFloat(), Color(35, 35, 35)
                )
                g2d.paint = gradient
                g2d.fillRect(0, 0, width, height)
                
                // 底部分割线
                g2d.color = Color(60, 60, 60)
                g2d.fillRect(0, height - 1, width, 1)
            }
        }
        
        statsPanel.border = JBUI.Borders.empty(20, 25, 20, 25)
        statsPanel.preferredSize = Dimension(statsPanel.preferredSize.width, 100)
        
        // 左侧：标题和进度
        val leftPanel = JPanel()
        leftPanel.layout = BoxLayout(leftPanel, BoxLayout.Y_AXIS)
        leftPanel.isOpaque = false
        
        val titleLabel = JBLabel("成就系统")
        titleLabel.font = titleLabel.font.deriveFont(Font.BOLD, 24f)
        titleLabel.foreground = Color.WHITE
        titleLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val progressLabel = JBLabel("已解锁 $unlockedCount / $totalAchievements ($percentage%)")
        progressLabel.font = progressLabel.font.deriveFont(14f)
        progressLabel.foreground = Color(180, 180, 180)
        progressLabel.border = JBUI.Borders.emptyTop(5)
        progressLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        leftPanel.add(titleLabel)
        leftPanel.add(progressLabel)
        
        // 右侧：今日解锁徽章
        val rightPanel = JPanel(FlowLayout(FlowLayout.RIGHT, 15, 0))
        rightPanel.isOpaque = false
        
        if (todayAchievements.isNotEmpty()) {
            val badgePanel = createTodayBadge(todayAchievements.size)
            rightPanel.add(badgePanel)
        }
        
        statsPanel.add(leftPanel, BorderLayout.WEST)
        statsPanel.add(rightPanel, BorderLayout.EAST)
        
        return statsPanel
    }
    
    /**
     * 创建今日解锁徽章
     */
    private fun createTodayBadge(count: Int): JComponent {
        val badge = object : JPanel() {
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 发光背景
                val gradient = GradientPaint(
                    0f, 0f, Color(255, 215, 0, 200),
                    width.toFloat(), height.toFloat(), Color(255, 140, 0, 200)
                )
                g2d.paint = gradient
                g2d.fillRoundRect(0, 0, width, height, 20, 20)
                
                // 外层发光
                g2d.color = Color(255, 215, 0, 80)
                g2d.stroke = BasicStroke(3f)
                g2d.drawRoundRect(2, 2, width - 4, height - 4, 18, 18)
            }
        }
        
        badge.layout = FlowLayout(FlowLayout.CENTER, 10, 8)
        badge.isOpaque = false
        badge.preferredSize = Dimension(120, 50)
        
        val iconLabel = JLabel("🎉")
        iconLabel.font = iconLabel.font.deriveFont(20f)
        
        val textLabel = JBLabel("今日 +$count")
        textLabel.font = textLabel.font.deriveFont(Font.BOLD, 16f)
        textLabel.foreground = Color.WHITE
        
        badge.add(iconLabel)
        badge.add(textLabel)
        
        return badge
    }
    
    /**
     * 创建今日成就展示区域
     */
    private fun createTodayAchievementsSection(todayAchievements: List<Achievement>): JComponent {
        val section = JPanel()
        section.layout = BoxLayout(section, BoxLayout.Y_AXIS)
        section.isOpaque = false
        section.border = JBUI.Borders.empty(20, 0, 25, 0)
        
        // 简洁的标题栏（去掉背景）
        val headerPanel = JPanel(FlowLayout(FlowLayout.LEFT, 10, 0))
        headerPanel.isOpaque = false
        headerPanel.border = JBUI.Borders.emptyBottom(15)
        headerPanel.maximumSize = Dimension(Int.MAX_VALUE, 40)
        
        val fireIcon = JLabel("🔥")
        fireIcon.font = fireIcon.font.deriveFont(20f)
        
        val headerLabel = JBLabel("今日解锁")
        headerLabel.font = headerLabel.font.deriveFont(Font.BOLD, 18f)
        headerLabel.foreground = Color(255, 180, 80)  // 柔和的橙色
        
        val countLabel = JBLabel("(${todayAchievements.size})")
        countLabel.font = countLabel.font.deriveFont(Font.PLAIN, 14f)
        countLabel.foreground = Color(150, 150, 150)  // 弱化数量显示
        
        headerPanel.add(fireIcon)
        headerPanel.add(headerLabel)
        headerPanel.add(countLabel)
        
        section.add(headerPanel)
        
        // 成就卡片容器（使用BorderLayout防止拉伸）
        for ((index, achievement) in todayAchievements.withIndex()) {
            // 创建一个包装容器，左右各留15px边距
            val cardWrapper = JPanel(BorderLayout())
            cardWrapper.isOpaque = false
            cardWrapper.border = JBUI.Borders.empty(
                if (index == 0) 10 else 6,  // 第一个卡片上边距10，其他6
                15,  // 左边距15
                if (index == todayAchievements.size - 1) 0 else 6,  // 最后一个下边距0，其他6
                15   // 右边距15
            )
            cardWrapper.maximumSize = Dimension(Int.MAX_VALUE, 100)
            
            val card = createPremiumTodayAchievementCard(achievement, index + 1)
            cardWrapper.add(card, BorderLayout.CENTER)
            
            section.add(cardWrapper)
        }
        
        return section
    }
    
    /**
     * 创建所有成就网格
     */
    private fun createAllAchievementsGrid(unlockedAchievements: List<Achievement>): JComponent {
        val panel = JPanel(BorderLayout(0, 15))
        panel.isOpaque = false
        
        // 分类标签
        val tabPanel = JBTabbedPane()
        tabPanel.tabPlacement = JTabbedPane.TOP
        
        val categories = mapOf(
            "💪 按行数" to listOf(
                AchievementType.WARM_UP, AchievementType.KEYBOARD_FLYING,
                AchievementType.HARD_WORKER, AchievementType.LEGENDARY_1000, AchievementType.CODE_MACHINE
            ),
            "🗑️ 按删除" to listOf(
                AchievementType.DELETE_DB, AchievementType.REFACTOR_MASTER, AchievementType.DELETE_AND_RUN
            ),
            "⏰ 按时间" to listOf(
                AchievementType.EARLY_BIRD, AchievementType.NIGHT_CODER,
                AchievementType.MARATHON_CODER, AchievementType.WEEKEND_WARRIOR
            ),
            "🔥 按连续性" to listOf(
                AchievementType.SIGN_IN_DAY1, AchievementType.CRAZY_7_DAYS,
                AchievementType.IRON_30_DAYS, AchievementType.DREAM_100_DAYS
            ),
            "🎭 网络热梗" to listOf(
                AchievementType.YYDS_FOREVER, AchievementType.ABSOLUTELY_AMAZING, AchievementType.CHICKEN_YOU_ARE_TOO_BEAUTIFUL,
                AchievementType.ART_IS_EXPLOSION, AchievementType.PURE_GRUDGE_HOLDER, AchievementType.LYING_FLAT,
                AchievementType.INVOLUTION_KING, AchievementType.NOT_UNUSABLE, AchievementType.SOCIAL_DEATH,
                AchievementType.TERRIFYING_WHEN_THINK, AchievementType.PARALYZED, AchievementType.CANT_HOLD_IT,
                AchievementType.HAVE_INSIDER_ABORT_DEAL, AchievementType.DEFENSE_BROKEN, AchievementType.WHAT_HAPPENED
            ),
            "🎮 趣味彩蛋" to listOf(
                AchievementType.BUG_HARVESTER, AchievementType.CTRL_S_BELIEVER,
                AchievementType.COPY_PASTE_MASTER, AchievementType.IDEA_RESTARTER, AchievementType.CONSOLE_LOG_PRIEST
            )
        )
        
        for ((categoryName, types) in categories) {
            val categoryPanel = createCategoryGrid(unlockedAchievements, types)
            tabPanel.addTab(categoryName, categoryPanel)
        }
        
        panel.add(tabPanel, BorderLayout.CENTER)
        
        return panel
    }
    
    /**
     * 创建分类网格
     */
    private fun createCategoryGrid(unlockedAchievements: List<Achievement>, types: List<AchievementType>): JComponent {
        val scrollPanel = JBScrollPane()
        scrollPanel.border = BorderFactory.createEmptyBorder()
        
        val gridPanel = JPanel(GridLayout(0, 1, 0, 12))
        gridPanel.background = JBColor(Color(30, 30, 30), Color(30, 30, 30))
        gridPanel.border = JBUI.Borders.empty(15)
        
        val unlockedTypes = unlockedAchievements.map { it.type }
        
        for (type in types) {
            val card = if (unlockedTypes.contains(type)) {
                val achievement = unlockedAchievements.find { it.type == type }!!
                createPremiumAchievementCard(achievement)
            } else {
                createPremiumLockedCard(type)
            }
            gridPanel.add(card)
        }
        
        scrollPanel.setViewportView(gridPanel)
        scrollPanel.viewport.background = gridPanel.background
        
        return scrollPanel
    }
    
    /**
     * 创建成就分类面板
     */
    private fun createCategoryPanel(unlockedAchievements: List<Achievement>, categoryTypes: List<AchievementType>): JComponent {
        val panel = JPanel()
        panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS)
        panel.border = JBUI.Borders.empty(15)
        panel.background = JBColor(Color(55, 55, 55), Color(55, 55, 55))
        
        // 已解锁的成就
        val unlockedTypes = unlockedAchievements.map { it.type }
        
        for (type in categoryTypes) {
            // 创建成就卡片（已解锁或未解锁）
            val card = if (unlockedTypes.contains(type)) {
                // 找到已解锁的成就
                val achievement = unlockedAchievements.find { it.type == type }!!
                createAchievementCard(achievement)
            } else {
                // 创建未解锁的成就卡片
                createLockedAchievementCard(type)
            }
            
            card.maximumSize = Dimension(Int.MAX_VALUE, card.preferredSize.height)
            panel.add(card)
            panel.add(Box.createVerticalStrut(12))
        }
        
        // 创建滚动面板
        val scrollPane = JBScrollPane(panel)
        scrollPane.border = BorderFactory.createEmptyBorder()
        scrollPane.background = panel.background
        scrollPane.viewport.background = panel.background
        
        return scrollPane
    }
    
    /**
     * 创建专业级今日成就卡片
     */
    private fun createPremiumTodayAchievementCard(achievement: Achievement, index: Int): JComponent {
        val achievementColor = getAchievementColor(achievement.type)
        
        val card = object : JPanel(BorderLayout(15, 0)) {
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 柔和的单色背景（降低饱和度）
                g2d.color = Color(50, 50, 55, 200)
                g2d.fillRoundRect(0, 0, width, height, 15, 15)
                
                // 左侧彩色条（代替整体边框，更简洁）
                g2d.color = achievementColor
                g2d.fillRoundRect(0, 0, 4, height, 15, 15)
                
                // 柔和的边框
                g2d.color = Color(achievementColor.red, achievementColor.green, achievementColor.blue, 80)
                g2d.stroke = BasicStroke(1.5f)
                g2d.drawRoundRect(0, 0, width - 1, height - 1, 15, 15)
                
                // 顶部细微高光
                g2d.color = Color(255, 255, 255, 15)
                val highlightGradient = GradientPaint(0f, 0f, g2d.color, 0f, height / 4f, Color(0, 0, 0, 0))
                g2d.paint = highlightGradient
                g2d.fillRoundRect(2, 2, width - 4, height / 4, 13, 13)
            }
        }
        
        // 调整边距，上下左右留白均匀
        card.border = JBUI.Borders.empty(16, 20, 16, 20)
        card.isOpaque = false
        card.preferredSize = Dimension(680, 88)
        card.maximumSize = Dimension(680, 88)  // 固定宽度，防止拉伸
        card.minimumSize = Dimension(680, 88)
        
        // 左侧：图标
        val leftPanel = JPanel(FlowLayout(FlowLayout.CENTER, 0, 0))
        leftPanel.isOpaque = false
        leftPanel.preferredSize = Dimension(60, 55)
        
        // 图标
        val iconLabel = JLabel(achievement.getIcon())
        iconLabel.font = Font("Apple Color Emoji", Font.PLAIN, 42)
        iconLabel.horizontalAlignment = SwingConstants.CENTER
        
        leftPanel.add(iconLabel)
        card.add(leftPanel, BorderLayout.WEST)
        
        // 中间内容
        val contentPanel = JPanel()
        contentPanel.layout = BoxLayout(contentPanel, BoxLayout.Y_AXIS)
        contentPanel.isOpaque = false
        contentPanel.border = JBUI.Borders.empty(0, 10, 0, 0)  // 左侧留白
        
        val nameLabel = JBLabel(achievement.getName())
        nameLabel.font = nameLabel.font.deriveFont(Font.BOLD, 17f)
        nameLabel.foreground = Color(245, 245, 245)
        nameLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val descLabel = JBLabel(achievement.getDescription())
        descLabel.font = descLabel.font.deriveFont(14f)
        descLabel.foreground = Color(190, 190, 190)
        descLabel.border = JBUI.Borders.emptyTop(5)
        descLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        contentPanel.add(nameLabel)
        contentPanel.add(descLabel)
        
        card.add(contentPanel, BorderLayout.CENTER)
        
        // 右侧：NEW标签（增加左边距）
        if (achievement.isNew()) {
            val badgeContainer = JPanel(FlowLayout(FlowLayout.RIGHT, 0, 0))
            badgeContainer.isOpaque = false
            badgeContainer.border = JBUI.Borders.emptyLeft(15)  // 与内容留白
            val newBadge = createSoftNewBadge()
            badgeContainer.add(newBadge)
            card.add(badgeContainer, BorderLayout.EAST)
        }
        
        return card
    }
    
    /**
     * 创建NEW标签
     */
    private fun createNewBadge(): JComponent {
        val badge = object : JPanel() {
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 渐变背景（红色到橙色）
                val gradient = GradientPaint(
                    0f, 0f, Color(255, 0, 100),
                    width.toFloat(), height.toFloat(), Color(255, 100, 0)
                )
                g2d.paint = gradient
                g2d.fillRoundRect(0, 0, width, height, 12, 12)
                
                // 外层光晕
                g2d.color = Color(255, 0, 100, 100)
                g2d.stroke = BasicStroke(2f)
                g2d.drawRoundRect(0, 0, width - 1, height - 1, 12, 12)
            }
        }
        
        badge.layout = FlowLayout(FlowLayout.CENTER, 8, 5)
        badge.isOpaque = false
        badge.preferredSize = Dimension(60, 30)
        
        val label = JBLabel("NEW")
        label.font = label.font.deriveFont(Font.BOLD, 12f)
        label.foreground = Color.WHITE
        
        badge.add(label)
        
        return badge
    }
    
    /**
     * 创建增强版NEW标签（用于今日成就）
     */
    private fun createEnhancedNewBadge(): JComponent {
        val badge = object : JPanel() {
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 多层渐变背景
                val gradient = LinearGradientPaint(
                    0f, 0f, width.toFloat(), height.toFloat(),
                    floatArrayOf(0f, 0.5f, 1f),
                    arrayOf(
                        Color(255, 50, 100),
                        Color(255, 80, 50),
                        Color(255, 120, 0)
                    )
                )
                g2d.paint = gradient
                g2d.fillRoundRect(0, 0, width, height, 15, 15)
                
                // 外层发光效果
                g2d.color = Color(255, 50, 100, 120)
                g2d.stroke = BasicStroke(3f)
                g2d.drawRoundRect(0, 0, width - 1, height - 1, 15, 15)
                
                // 内层高光
                g2d.color = Color(255, 255, 255, 60)
                g2d.stroke = BasicStroke(1.5f)
                g2d.drawRoundRect(2, 2, width - 4, height - 4, 13, 13)
            }
        }
        
        badge.layout = FlowLayout(FlowLayout.CENTER, 10, 8)
        badge.isOpaque = false
        badge.preferredSize = Dimension(70, 40)
        
        val label = JBLabel("NEW")
        label.font = label.font.deriveFont(Font.BOLD, 14f)
        label.foreground = Color.WHITE
        
        badge.add(label)
        
        return badge
    }
    
    /**
     * 创建柔和版NEW标签（用于今日成就）
     */
    private fun createSoftNewBadge(): JComponent {
        val badge = object : JPanel() {
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 柔和的单色背景（降低饱和度）
                g2d.color = Color(200, 80, 60, 180)  // 柔和的橙红色
                g2d.fillRoundRect(0, 0, width, height, 10, 10)
                
                // 细边框
                g2d.color = Color(220, 100, 80, 150)
                g2d.stroke = BasicStroke(1f)
                g2d.drawRoundRect(0, 0, width - 1, height - 1, 10, 10)
            }
        }
        
        badge.layout = FlowLayout(FlowLayout.CENTER, 8, 4)
        badge.isOpaque = false
        badge.preferredSize = Dimension(55, 28)
        
        val label = JBLabel("NEW")
        label.font = label.font.deriveFont(Font.BOLD, 11f)
        label.foreground = Color(255, 255, 255)
        
        badge.add(label)
        
        return badge
    }
    
    /**
     * 创建专业级成就卡片（已解锁）
     */
    private fun createPremiumAchievementCard(achievement: Achievement): JComponent {
        val achievementColor = getAchievementColor(achievement.type)
        
        val card = object : JPanel(BorderLayout(15, 0)) {
            private var isHovered = false
            
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 主背景
                g2d.color = Color(45, 45, 45)
                g2d.fillRoundRect(0, 0, width, height, 12, 12)
                
                // 左侧彩色条
                g2d.color = achievementColor
                g2d.fillRoundRect(0, 0, 6, height, 12, 12)
                
                // 边框
                g2d.color = if (isHovered) achievementColor else Color(70, 70, 70)
                g2d.stroke = BasicStroke(if (isHovered) 2f else 1f)
                g2d.drawRoundRect(0, 0, width - 1, height - 1, 12, 12)
                
                // 悬停高光
                if (isHovered) {
                    g2d.color = Color(255, 255, 255, 15)
                    g2d.fillRoundRect(2, 2, width - 4, height / 2, 10, 10)
                }
            }
        }
        
        card.border = JBUI.Borders.empty(15, 18, 15, 18)
        card.isOpaque = false
        card.preferredSize = Dimension(card.preferredSize.width, 85)
        
        // 鼠标交互
        card.addMouseListener(object : java.awt.event.MouseAdapter() {
            override fun mouseEntered(e: java.awt.event.MouseEvent?) {
                try {
                    val field = card.javaClass.getDeclaredField("isHovered")
                    field.isAccessible = true
                    field.set(card, true)
                    card.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
                    card.repaint()
                } catch (ex: Exception) {}
            }
            
            override fun mouseExited(e: java.awt.event.MouseEvent?) {
                try {
                    val field = card.javaClass.getDeclaredField("isHovered")
                    field.isAccessible = true
                    field.set(card, false)
                    card.cursor = Cursor.getDefaultCursor()
                    card.repaint()
                } catch (ex: Exception) {}
            }
        })
        
        // 图标
        val iconLabel = JLabel(achievement.getIcon())
        iconLabel.font = Font("Apple Color Emoji", Font.PLAIN, 30)
        iconLabel.horizontalAlignment = SwingConstants.CENTER
        iconLabel.preferredSize = Dimension(45, 45)
        card.add(iconLabel, BorderLayout.WEST)
        
        // 内容
        val contentPanel = JPanel()
        contentPanel.layout = BoxLayout(contentPanel, BoxLayout.Y_AXIS)
        contentPanel.isOpaque = false
        
        val nameLabel = JBLabel(achievement.getName())
        nameLabel.font = nameLabel.font.deriveFont(Font.BOLD, 15f)
        nameLabel.foreground = Color.WHITE
        nameLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val descLabel = JBLabel(achievement.getDescription())
        descLabel.font = descLabel.font.deriveFont(13f)
        descLabel.foreground = Color(170, 170, 170)
        descLabel.border = JBUI.Borders.emptyTop(4)
        descLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        contentPanel.add(nameLabel)
        contentPanel.add(descLabel)
        
        card.add(contentPanel, BorderLayout.CENTER)
        
        return card
    }
    
    /**
     * 创建专业级未解锁卡片
     */
    private fun createPremiumLockedCard(type: AchievementType): JComponent {
        val achievement = Achievement(type = type)
        
        val card = object : JPanel(BorderLayout(15, 0)) {
            private var isHovered = false
            
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 主背景
                g2d.color = Color(40, 40, 40)
                g2d.fillRoundRect(0, 0, width, height, 12, 12)
                
                // 边框
                g2d.color = Color(60, 60, 60)
                g2d.stroke = BasicStroke(1f)
                g2d.drawRoundRect(0, 0, width - 1, height - 1, 12, 12)
                
                // 悬停效果
                if (isHovered) {
                    g2d.color = Color(255, 255, 255, 8)
                    g2d.fillRoundRect(2, 2, width - 4, height - 4, 10, 10)
                }
            }
        }
        
        card.border = JBUI.Borders.empty(15, 18, 15, 18)
        card.isOpaque = false
        card.preferredSize = Dimension(card.preferredSize.width, 85)
        
        // 鼠标交互
        card.addMouseListener(object : java.awt.event.MouseAdapter() {
            override fun mouseEntered(e: java.awt.event.MouseEvent?) {
                try {
                    val field = card.javaClass.getDeclaredField("isHovered")
                    field.isAccessible = true
                    field.set(card, true)
                    card.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
                    card.repaint()
                } catch (ex: Exception) {}
            }
            
            override fun mouseExited(e: java.awt.event.MouseEvent?) {
                try {
                    val field = card.javaClass.getDeclaredField("isHovered")
                    field.isAccessible = true
                    field.set(card, false)
                    card.cursor = Cursor.getDefaultCursor()
                    card.repaint()
                } catch (ex: Exception) {}
            }
        })
        
        // 锁图标
        val iconLabel = JLabel("🔒")
        iconLabel.font = Font("Apple Color Emoji", Font.PLAIN, 30)
        iconLabel.horizontalAlignment = SwingConstants.CENTER
        iconLabel.preferredSize = Dimension(45, 45)
        card.add(iconLabel, BorderLayout.WEST)
        
        // 内容
        val contentPanel = JPanel()
        contentPanel.layout = BoxLayout(contentPanel, BoxLayout.Y_AXIS)
        contentPanel.isOpaque = false
        
        val nameLabel = JBLabel(achievement.getName())
        nameLabel.font = nameLabel.font.deriveFont(Font.BOLD, 15f)
        nameLabel.foreground = Color(120, 120, 120)
        nameLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val descLabel = JBLabel("未解锁")
        descLabel.font = descLabel.font.deriveFont(13f)
        descLabel.foreground = Color(90, 90, 90)
        descLabel.border = JBUI.Borders.emptyTop(4)
        descLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        contentPanel.add(nameLabel)
        contentPanel.add(descLabel)
        
        card.add(contentPanel, BorderLayout.CENTER)
        
        return card
    }
    
    /**
     * 创建今日成就卡片（旧版，保留兼容性）
     */
    private fun createTodayAchievementCard(achievement: Achievement): JComponent {
        val achievementColor = getAchievementColor(achievement.type)
        
        // 自定义面板，带光影效果
        val panel = object : JPanel(BorderLayout(15, 0)) {
            private var isHovered = false
            private var shadowAlpha = 0.3f
            
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 绘制外层阴影（光影层次）
                val shadowSize = if (isHovered) 8 else 5
                for (i in shadowSize downTo 0) {
                    val alpha = (shadowAlpha * (shadowSize - i) / shadowSize).coerceIn(0f, 1f)
                    g2d.color = Color(0, 0, 0, (alpha * 100).toInt())
                    g2d.fillRoundRect(i, i, width - i * 2, height - i * 2, 12, 12)
                }
                
                // 绘制主背景
                g2d.color = background
                g2d.fillRoundRect(0, 0, width, height, 12, 12)
                
                // 绘制彩色边框（带发光效果）
                if (isHovered) {
                    // 外层发光
                    g2d.color = Color(achievementColor.red, achievementColor.green, achievementColor.blue, 100)
                    g2d.stroke = BasicStroke(5f)
                    g2d.drawRoundRect(2, 2, width - 4, height - 4, 12, 12)
                }
                
                // 主边框
                g2d.color = achievementColor
                g2d.stroke = BasicStroke(3f)
                g2d.drawRoundRect(0, 0, width - 1, height - 1, 12, 12)
                
                // 内层高光
                g2d.color = Color(255, 255, 255, if (isHovered) 40 else 20)
                val gradient = GradientPaint(0f, 0f, g2d.color, 0f, height / 2f, Color(255, 255, 255, 0))
                g2d.paint = gradient
                g2d.fillRoundRect(3, 3, width - 6, height / 2, 10, 10)
            }
        }
        
        panel.border = EmptyBorder(15, 15, 15, 15)
        panel.background = JBColor(Color(70, 70, 70), Color(70, 70, 70))
        panel.isOpaque = false
        
        // 添加鼠标悬停动画
        panel.addMouseListener(object : java.awt.event.MouseAdapter() {
            override fun mouseEntered(e: java.awt.event.MouseEvent?) {
                (panel as? JPanel)?.let { p ->
                    try {
                        val field = p.javaClass.getDeclaredField("isHovered")
                        field.isAccessible = true
                        field.set(p, true)
                    } catch (ex: Exception) {
                        // 忽略反射异常
                    }
                }
                panel.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
                panel.repaint()
            }
            
            override fun mouseExited(e: java.awt.event.MouseEvent?) {
                (panel as? JPanel)?.let { p ->
                    try {
                        val field = p.javaClass.getDeclaredField("isHovered")
                        field.isAccessible = true
                        field.set(p, false)
                    } catch (ex: Exception) {
                        // 忽略反射异常
                    }
                }
                panel.cursor = Cursor.getDefaultCursor()
                panel.repaint()
            }
        })
        
        // 左侧：成就图标
        val iconLabel = JLabel(achievement.getIcon())
        iconLabel.font = Font("Apple Color Emoji", Font.PLAIN, 32)
        iconLabel.horizontalAlignment = SwingConstants.CENTER
        iconLabel.preferredSize = Dimension(45, 45)
        panel.add(iconLabel, BorderLayout.WEST)
        
        // 中间：成就信息
        val infoPanel = JPanel(BorderLayout(0, 8))
        infoPanel.background = Color(0, 0, 0, 0)
        infoPanel.isOpaque = false
        
        val nameLabel = JBLabel("「${achievement.getName()}」 —— ${achievement.getDescription()} 🚀")
        nameLabel.font = nameLabel.font.deriveFont(Font.BOLD, 16f)
        nameLabel.foreground = JBColor.WHITE
        
        infoPanel.add(nameLabel, BorderLayout.CENTER)
        
        panel.add(infoPanel, BorderLayout.CENTER)
        
        // 右侧：火焰图标（带动画）
        val fireLabel = object : JLabel("🔥") {
            private var scale = 1.0f
            private val timer = javax.swing.Timer(500) {
                scale = if (scale == 1.0f) 1.2f else 1.0f
                font = font.deriveFont(28f * scale)
                repaint()
            }
            
            init {
                timer.start()
            }
        }
        fireLabel.font = fireLabel.font.deriveFont(28f)
        panel.add(fireLabel, BorderLayout.EAST)
        
        return panel
    }
    
    /**
     * 创建成就卡片（带光影和动画）
     */
    private fun createAchievementCard(achievement: Achievement): JComponent {
        val achievementColor = getAchievementColor(achievement.type)
        val bgColor = Color(
            (achievementColor.red * 0.3).toInt(),
            (achievementColor.green * 0.3).toInt(),
            (achievementColor.blue * 0.3).toInt()
        )
        
        // 自定义面板，带光影效果
        val panel = object : JPanel(BorderLayout(12, 0)) {
            private var isHovered = false
            private var elevation = 3
            
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 绘制阴影（光影层次）
                val shadowSize = if (isHovered) elevation + 2 else elevation
                for (i in shadowSize downTo 0) {
                    val alpha = (50 * (shadowSize - i) / shadowSize).coerceIn(0, 255)
                    g2d.color = Color(0, 0, 0, alpha)
                    g2d.fillRoundRect(i, i, width - i * 2, height - i * 2, 10, 10)
                }
                
                // 绘制主背景
                g2d.color = bgColor
                g2d.fillRoundRect(0, 0, width, height, 10, 10)
                
                // 绘制边框
                g2d.color = achievementColor
                g2d.stroke = BasicStroke(if (isHovered) 3f else 2f)
                g2d.drawRoundRect(1, 1, width - 2, height - 2, 10, 10)
                
                // 内层高光
                g2d.color = Color(255, 255, 255, if (isHovered) 30 else 15)
                val gradient = GradientPaint(0f, 0f, g2d.color, 0f, height / 3f, Color(255, 255, 255, 0))
                g2d.paint = gradient
                g2d.fillRoundRect(2, 2, width - 4, height / 3, 8, 8)
            }
        }
        
        panel.border = EmptyBorder(12, 12, 12, 12)
        panel.isOpaque = false
        
        // 添加鼠标悬停动画
        panel.addMouseListener(object : java.awt.event.MouseAdapter() {
            override fun mouseEntered(e: java.awt.event.MouseEvent?) {
                (panel as? JPanel)?.let { p ->
                    try {
                        val field = p.javaClass.getDeclaredField("isHovered")
                        field.isAccessible = true
                        field.set(p, true)
                    } catch (ex: Exception) {
                        // 忽略反射异常
                    }
                }
                panel.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
                panel.repaint()
            }
            
            override fun mouseExited(e: java.awt.event.MouseEvent?) {
                (panel as? JPanel)?.let { p ->
                    try {
                        val field = p.javaClass.getDeclaredField("isHovered")
                        field.isAccessible = true
                        field.set(p, false)
                    } catch (ex: Exception) {
                        // 忽略反射异常
                    }
                }
                panel.cursor = Cursor.getDefaultCursor()
                panel.repaint()
            }
        })
        
        val iconLabel = JLabel(achievement.getIcon())
        iconLabel.font = Font("Apple Color Emoji", Font.PLAIN, 28)
        iconLabel.horizontalAlignment = SwingConstants.CENTER
        iconLabel.preferredSize = Dimension(40, 40)
        panel.add(iconLabel, BorderLayout.WEST)
        
        val infoPanel = JPanel(BorderLayout(0, 6))
        infoPanel.background = Color(0, 0, 0, 0)
        infoPanel.isOpaque = false
        
        val nameLabel = JBLabel(achievement.getName())
        nameLabel.font = nameLabel.font.deriveFont(Font.BOLD, 15f)
        nameLabel.foreground = JBColor.WHITE
        
        val descLabel = JBLabel(achievement.getDescription())
        descLabel.foreground = JBColor.LIGHT_GRAY
        descLabel.font = descLabel.font.deriveFont(13f)
        
        infoPanel.add(nameLabel, BorderLayout.NORTH)
        infoPanel.add(descLabel, BorderLayout.CENTER)
        
        panel.add(infoPanel, BorderLayout.CENTER)
        
        return panel
    }
    
    /**
     * 创建未解锁的成就卡片（带光影效果）
     */
    private fun createLockedAchievementCard(type: AchievementType): JComponent {
        val bgColor = Color(50, 50, 50)
        val borderColor = Color(100, 100, 100)
        
        // 自定义面板，带光影效果
        val panel = object : JPanel(BorderLayout(12, 0)) {
            private var isHovered = false
            
            override fun paintComponent(g: Graphics) {
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 绘制阴影（较浅）
                val shadowSize = 2
                for (i in shadowSize downTo 0) {
                    val alpha = (30 * (shadowSize - i) / shadowSize).coerceIn(0, 255)
                    g2d.color = Color(0, 0, 0, alpha)
                    g2d.fillRoundRect(i, i, width - i * 2, height - i * 2, 10, 10)
                }
                
                // 绘制主背景
                g2d.color = bgColor
                g2d.fillRoundRect(0, 0, width, height, 10, 10)
                
                // 绘制边框
                g2d.color = borderColor
                g2d.stroke = BasicStroke(1f)
                g2d.drawRoundRect(0, 0, width - 1, height - 1, 10, 10)
                
                // 鼠标悬停时显示轻微高光
                if (isHovered) {
                    g2d.color = Color(255, 255, 255, 10)
                    g2d.fillRoundRect(2, 2, width - 4, height / 3, 8, 8)
                }
            }
        }
        
        panel.border = EmptyBorder(12, 12, 12, 12)
        panel.isOpaque = false
        
        // 添加鼠标悬停效果
        panel.addMouseListener(object : java.awt.event.MouseAdapter() {
            override fun mouseEntered(e: java.awt.event.MouseEvent?) {
                (panel as? JPanel)?.let { p ->
                    try {
                        val field = p.javaClass.getDeclaredField("isHovered")
                        field.isAccessible = true
                        field.set(p, true)
                    } catch (ex: Exception) {
                        // 忽略反射异常
                    }
                }
                panel.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
                panel.repaint()
            }
            
            override fun mouseExited(e: java.awt.event.MouseEvent?) {
                (panel as? JPanel)?.let { p ->
                    try {
                        val field = p.javaClass.getDeclaredField("isHovered")
                        field.isAccessible = true
                        field.set(p, false)
                    } catch (ex: Exception) {
                        // 忽略反射异常
                    }
                }
                panel.cursor = Cursor.getDefaultCursor()
                panel.repaint()
            }
        })
        
        val achievement = Achievement(type = type)
        
        val iconLabel = JLabel("🔒")
        iconLabel.font = Font("Apple Color Emoji", Font.PLAIN, 28)
        iconLabel.horizontalAlignment = SwingConstants.CENTER
        iconLabel.preferredSize = Dimension(40, 40)
        panel.add(iconLabel, BorderLayout.WEST)
        
        val infoPanel = JPanel(BorderLayout(0, 6))
        infoPanel.background = Color(0, 0, 0, 0)
        infoPanel.isOpaque = false
        
        val nameLabel = JBLabel(achievement.getName())
        nameLabel.font = nameLabel.font.deriveFont(Font.BOLD, 15f)
        nameLabel.foreground = JBColor(Color(130, 130, 130), Color(130, 130, 130))
        
        val descLabel = JBLabel("未解锁")
        descLabel.foreground = JBColor(Color(100, 100, 100), Color(100, 100, 100))
        descLabel.font = descLabel.font.deriveFont(13f)
        
        infoPanel.add(nameLabel, BorderLayout.NORTH)
        infoPanel.add(descLabel, BorderLayout.CENTER)
        
        panel.add(infoPanel, BorderLayout.CENTER)
        
        return panel
    }
    
    /**
     * 创建现代化统计卡片（带渐变色）
     */
    private fun createModernStatCard(
        title: String, 
        value: String, 
        icon: String,
        color1: Color, 
        color2: Color
    ): JComponent {
        val panel = object : JPanel(BorderLayout(0, 10)) {
            override fun paintComponent(g: Graphics) {
                super.paintComponent(g)
                val g2d = g as Graphics2D
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
                
                // 绘制渐变背景
                val gradient = GradientPaint(0f, 0f, color1, width.toFloat(), height.toFloat(), color2)
                g2d.paint = gradient
                g2d.fillRoundRect(0, 0, width, height, 15, 15)
            }
        }
        
        panel.border = EmptyBorder(20, 20, 20, 20)
        panel.isOpaque = false
        
        // 顶部：图标
        val iconLabel = JBLabel(icon)
        iconLabel.font = iconLabel.font.deriveFont(32f)
        iconLabel.foreground = Color.WHITE
        iconLabel.horizontalAlignment = SwingConstants.CENTER
        panel.add(iconLabel, BorderLayout.NORTH)
        
        // 中间：标题
        val titleLabel = JBLabel(title)
        titleLabel.font = titleLabel.font.deriveFont(Font.PLAIN, 13f)
        titleLabel.foreground = Color.WHITE
        titleLabel.horizontalAlignment = SwingConstants.CENTER
        panel.add(titleLabel, BorderLayout.CENTER)
        
        // 底部：数值
        val valueLabel = JBLabel(value)
        valueLabel.font = valueLabel.font.deriveFont(Font.BOLD, 36f)
        valueLabel.foreground = Color.WHITE
        valueLabel.horizontalAlignment = SwingConstants.CENTER
        panel.add(valueLabel, BorderLayout.SOUTH)
        
        return panel
    }
    
    /**
     * 创建报告按钮
     */
    private fun createReportButton(text: String, reportType: ReportType): JButton {
        val button = JButton(text)
        button.font = button.font.deriveFont(Font.BOLD, 13f)
        button.background = JBColor(Color(33, 150, 243), Color(33, 150, 243))
        button.foreground = Color.WHITE
        button.isFocusPainted = false
        button.border = BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(JBColor(Color(30, 136, 229), Color(30, 136, 229)), 1),
            EmptyBorder(8, 20, 8, 20)
        )
        button.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
        
        button.addActionListener {
            LOG.info("点击生成${reportType}报告按钮")
            try {
                val reportDialog = ReportDialog(project, reportType)
                reportDialog.show()
            } catch (e: Exception) {
                LOG.error("生成报告出错", e)
                JOptionPane.showMessageDialog(
                    button,
                    "生成报告时出错: ${e.message}",
                    "错误",
                    JOptionPane.ERROR_MESSAGE
                )
            }
        }
        
        return button
    }
    
    /**
     * 生成总结文字
     */
    private fun generateSummaryText(addedLines: Int, todayStats: List<CodeStats>): String {
        if (todayStats.isEmpty()) {
            return "今天还没有写代码呢，快去敲代码吧！⌨️"
        }
        
        val mainLanguage = todayStats.maxByOrNull { it.addedLines }?.language ?: "未知语言"
        
        return when {
            addedLines == 0 -> "今天还没有写代码呢，快去敲代码吧！⌨️"
            addedLines < 50 -> "你今天写了 $addedLines 行代码，$mainLanguage 小试牛刀！🎯"
            addedLines < 100 -> "你今天写了 $addedLines 行代码，$mainLanguage 渐入佳境！💪"
            addedLines < 300 -> "你今天狠狠地写了 $addedLines 行代码，$mainLanguage 直呼内行！🔥"
            addedLines < 500 -> "你今天疯狂输出了 $addedLines 行代码，$mainLanguage 已被你征服！🚀"
            else -> "你今天简直是代码机器！$addedLines 行代码，$mainLanguage 瑟瑟发抖！🤖"
        }
    }
    
    /**
     * 创建统计卡片（旧版本，保留用于其他地方）
     */
    private fun createStatCard(title: String, value: String, accentColor: Color): JComponent {
        val panel = JPanel(BorderLayout(0, 5))
        panel.border = BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(accentColor, 2),
            EmptyBorder(15, 15, 15, 15)
        )
        
        val titleLabel = JBLabel(title)
        titleLabel.font = titleLabel.font.deriveFont(Font.BOLD, 14f)
        panel.add(titleLabel, BorderLayout.NORTH)
        
        val valueLabel = JBLabel(value)
        valueLabel.font = valueLabel.font.deriveFont(Font.BOLD, 24f)
        valueLabel.foreground = accentColor
        panel.add(valueLabel, BorderLayout.CENTER)
        
        return panel
    }
    
    /**
     * 获取成就颜色
     */
    private fun getAchievementColor(type: AchievementType): Color {
        return when (type) {
            // 按行数
            AchievementType.WARM_UP -> JBColor(Color(255, 152, 0), Color(255, 152, 0))
            AchievementType.KEYBOARD_FLYING -> JBColor(Color(76, 175, 80), Color(76, 175, 80))
            AchievementType.HARD_WORKER -> JBColor(Color(33, 150, 243), Color(33, 150, 243))
            AchievementType.LEGENDARY_1000 -> JBColor(Color(156, 39, 176), Color(156, 39, 176))
            AchievementType.CODE_MACHINE -> JBColor(Color(233, 30, 99), Color(233, 30, 99))
            
            // 按删除
            AchievementType.DELETE_DB -> JBColor(Color(244, 67, 54), Color(244, 67, 54))
            AchievementType.REFACTOR_MASTER -> JBColor(Color(121, 85, 72), Color(121, 85, 72))
            AchievementType.DELETE_AND_RUN -> JBColor(Color(0, 150, 136), Color(0, 150, 136))
            
            // 按时间
            AchievementType.EARLY_BIRD -> JBColor(Color(255, 193, 7), Color(255, 193, 7))
            AchievementType.NIGHT_CODER -> JBColor(Color(63, 81, 181), Color(63, 81, 181))
            AchievementType.MARATHON_CODER -> JBColor(Color(255, 87, 34), Color(255, 87, 34))
            AchievementType.WEEKEND_WARRIOR -> JBColor(Color(96, 125, 139), Color(96, 125, 139))
            
            // 按连续性
            AchievementType.SIGN_IN_DAY1 -> JBColor(Color(158, 158, 158), Color(158, 158, 158))
            AchievementType.CRAZY_7_DAYS -> JBColor(Color(3, 169, 244), Color(3, 169, 244))
            AchievementType.IRON_30_DAYS -> JBColor(Color(139, 195, 74), Color(139, 195, 74))
            AchievementType.DREAM_100_DAYS -> JBColor(Color(255, 235, 59), Color(255, 235, 59))
            
            // 趣味彩蛋
            AchievementType.BUG_HARVESTER -> JBColor(Color(103, 58, 183), Color(103, 58, 183))
            AchievementType.CTRL_S_BELIEVER -> JBColor(Color(0, 188, 212), Color(0, 188, 212))
            AchievementType.COPY_PASTE_MASTER -> JBColor(Color(233, 30, 99), Color(233, 30, 99))
            AchievementType.IDEA_RESTARTER -> JBColor(Color(255, 152, 0), Color(255, 152, 0))
            AchievementType.CONSOLE_LOG_PRIEST -> JBColor(Color(76, 175, 80), Color(76, 175, 80))
            
            // 网络热梗成就
            AchievementType.CHICKEN_YOU_ARE_TOO_BEAUTIFUL -> JBColor(Color(255, 87, 34), Color(255, 87, 34))
            AchievementType.HAVE_INSIDER_ABORT_DEAL -> JBColor(Color(244, 67, 54), Color(244, 67, 54))
            AchievementType.ABSOLUTELY_AMAZING -> JBColor(Color(255, 193, 7), Color(255, 193, 7))
            AchievementType.NOT_UNUSABLE -> JBColor(Color(158, 158, 158), Color(158, 158, 158))
            AchievementType.TERRIFYING_WHEN_THINK -> JBColor(Color(103, 58, 183), Color(103, 58, 183))
            AchievementType.PARALYZED -> JBColor(Color(96, 125, 139), Color(96, 125, 139))
            AchievementType.CANT_HOLD_IT -> JBColor(Color(255, 152, 0), Color(255, 152, 0))
            AchievementType.PURE_GRUDGE_HOLDER -> JBColor(Color(63, 81, 181), Color(63, 81, 181))
            AchievementType.DEFENSE_BROKEN -> JBColor(Color(233, 30, 99), Color(233, 30, 99))
            AchievementType.ART_IS_EXPLOSION -> JBColor(Color(244, 67, 54), Color(244, 67, 54))
            AchievementType.YYDS_FOREVER -> JBColor(Color(255, 215, 0), Color(255, 215, 0))
            AchievementType.WHAT_HAPPENED -> JBColor(Color(255, 87, 34), Color(255, 87, 34))
            AchievementType.SOCIAL_DEATH -> JBColor(Color(233, 30, 99), Color(233, 30, 99))
            AchievementType.LYING_FLAT -> JBColor(Color(121, 85, 72), Color(121, 85, 72))
            AchievementType.INVOLUTION_KING -> JBColor(Color(156, 39, 176), Color(156, 39, 176))
        }
    }
    
    /**
     * 创建智能推荐面板
     */
    private fun createRecommendationPanel(): JComponent {
        val panel = JPanel(BorderLayout())
        panel.background = JBColor.background()
        panel.border = JBUI.Borders.empty(20, 25, 20, 25) // 增加左右边距，保持对称
        
        val scrollPane = JBScrollPane()
        val contentPanel = JPanel()
        contentPanel.layout = BoxLayout(contentPanel, BoxLayout.Y_AXIS)
        contentPanel.background = JBColor.background()
        
        try {
            val recommendations = recommendationService.getSmartRecommendations()
            
            if (recommendations.isEmpty()) {
                val emptyLabel = JBLabel("太棒了！你已经解锁了所有可用的成就！")
                emptyLabel.font = emptyLabel.font.deriveFont(16f)
                emptyLabel.horizontalAlignment = SwingConstants.CENTER
                contentPanel.add(emptyLabel)
            } else {
                // 标题
                val titleLabel = JBLabel("智能成就推荐")
                titleLabel.font = titleLabel.font.deriveFont(Font.BOLD, 18f)
                contentPanel.add(titleLabel)
                contentPanel.add(Box.createVerticalStrut(15))
                
                recommendations.forEach { rec ->
                    val card = createRecommendationCard(rec)
                    contentPanel.add(card)
                    contentPanel.add(Box.createVerticalStrut(10))
                }
            }
        } catch (e: Exception) {
            LOG.error("创建推荐面板失败", e)
            val errorLabel = JBLabel("加载推荐失败: ${e.message}")
            errorLabel.foreground = JBColor.RED
            contentPanel.add(errorLabel)
        }
        
        scrollPane.setViewportView(contentPanel)
        scrollPane.border = BorderFactory.createEmptyBorder()
        panel.add(scrollPane, BorderLayout.CENTER)
        
        return panel
    }
    
    /**
     * 创建单个推荐卡片
     */
    private fun createRecommendationCard(rec: RecommendationService.AchievementRecommendation): JPanel {
        val card = JPanel(BorderLayout())
        card.background = JBColor.background()
        card.border = JBUI.Borders.compound(
            JBUI.Borders.customLine(JBColor.border()),
            JBUI.Borders.empty(18, 25, 18, 25) // 增加内边距，让内容更宽松
        )
        
        val priorityColor = when (rec.priority) {
            RecommendationService.RecommendationPriority.IMMEDIATE -> JBColor(Color(255, 107, 107), Color(255, 107, 107))
            RecommendationService.RecommendationPriority.TODAY -> JBColor(Color(78, 205, 196), Color(78, 205, 196))
            RecommendationService.RecommendationPriority.THIS_WEEK -> JBColor(Color(69, 183, 209), Color(69, 183, 209))
            else -> JBColor(Color(158, 158, 158), Color(158, 158, 158))
        }
        
        // 中间：成就信息（现在占据整个中央区域）
        val centerPanel = JPanel()
        centerPanel.layout = BoxLayout(centerPanel, BoxLayout.Y_AXIS)
        centerPanel.background = JBColor.background()
        
        val nameLabel = JBLabel(rec.achievement.getName())
        nameLabel.font = nameLabel.font.deriveFont(Font.BOLD, 17f)
        nameLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val descLabel = JBLabel("<html>${rec.achievement.getDescription()}</html>")
        descLabel.font = descLabel.font.deriveFont(13f)
        descLabel.foreground = JBColor.GRAY
        descLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val progressLabel = JBLabel("进度: ${rec.progress.currentValue}/${rec.progress.targetValue} (${rec.progress.progressPercent}%)")
        progressLabel.font = progressLabel.font.deriveFont(12f)
        progressLabel.foreground = JBColor.BLUE
        progressLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val recommendationLabel = JBLabel("<html><b>推荐:</b> ${rec.recommendation}</html>")
        recommendationLabel.font = recommendationLabel.font.deriveFont(13f)
        recommendationLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val actionLabel = JBLabel("<html><b>建议:</b> ${rec.actionSuggestion}</html>")
        actionLabel.font = actionLabel.font.deriveFont(12f)
        actionLabel.foreground = JBColor(Color(76, 175, 80), Color(76, 175, 80))
        actionLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        centerPanel.add(nameLabel)
        centerPanel.add(Box.createVerticalStrut(3))
        centerPanel.add(descLabel)
        centerPanel.add(Box.createVerticalStrut(6))
        centerPanel.add(progressLabel)
        centerPanel.add(Box.createVerticalStrut(8))
        centerPanel.add(recommendationLabel)
        centerPanel.add(Box.createVerticalStrut(4))
        centerPanel.add(actionLabel)
        
        // 右侧：优先级标签
        val rightPanel = JPanel()
        rightPanel.layout = BoxLayout(rightPanel, BoxLayout.Y_AXIS)
        rightPanel.background = JBColor.background()
        
        val priorityTag = JBLabel(rec.priority.displayName)
        priorityTag.font = priorityTag.font.deriveFont(Font.BOLD, 11f)
        priorityTag.foreground = Color.WHITE
        priorityTag.isOpaque = true
        priorityTag.background = priorityColor
        priorityTag.border = JBUI.Borders.empty(5, 10)
        priorityTag.horizontalAlignment = SwingConstants.CENTER
        
        val timeLabel = JBLabel(rec.estimatedTime)
        timeLabel.font = timeLabel.font.deriveFont(11f)
        timeLabel.foreground = JBColor.GRAY
        timeLabel.horizontalAlignment = SwingConstants.CENTER
        
        rightPanel.add(priorityTag)
        rightPanel.add(Box.createVerticalStrut(10))
        rightPanel.add(timeLabel)
        rightPanel.add(Box.createVerticalGlue())
        
        // 右侧面板宽度
        rightPanel.preferredSize = Dimension(90, rightPanel.preferredSize.height)
        rightPanel.minimumSize = Dimension(90, rightPanel.minimumSize.height)
        rightPanel.maximumSize = Dimension(90, rightPanel.maximumSize.height)
        
        card.add(centerPanel, BorderLayout.CENTER)
        card.add(rightPanel, BorderLayout.EAST)
        
        return card
    }
    
    /**
     * 创建导出分享面板
     */
    private fun createExportPanel(): JComponent {
        val panel = JPanel(BorderLayout())
        panel.background = JBColor.background()
        panel.border = JBUI.Borders.empty(20)
        
        val contentPanel = JPanel()
        contentPanel.layout = BoxLayout(contentPanel, BoxLayout.Y_AXIS)
        contentPanel.background = JBColor.background()
        
        // 数据导出卡片
        val exportCard = createFunctionCard(
            "数据导出",
            "将您的编程数据导出为不同格式，支持多种主流数据格式",
            listOf(
                "导出为JSON" to { exportService.exportData(ExportService.ExportFormat.JSON) },
                "导出为CSV" to { exportService.exportData(ExportService.ExportFormat.CSV) },
                "导出为Markdown" to { exportService.exportData(ExportService.ExportFormat.MARKDOWN) }
            )
        )
        
        // 分享卡片
        val shareCard = createFunctionCard(
            "分享卡片",
            "生成精美的成就分享图片，让您的编程成果更具社交价值",
            listOf(
                "成就分享卡" to { exportService.generateShareCard(ExportService.ShareCardType.ACHIEVEMENT) },
                "日度总结卡" to { exportService.generateShareCard(ExportService.ShareCardType.DAILY_SUMMARY) },
                "年度报告卡" to { exportService.generateShareCard(ExportService.ShareCardType.ANNUAL_REPORT) }
            )
        )
        
        // 数据预览卡片
        val previewCard = createDataPreviewCard()
        
        contentPanel.add(exportCard)
        contentPanel.add(Box.createVerticalStrut(20))
        contentPanel.add(shareCard)
        contentPanel.add(Box.createVerticalStrut(20))
        contentPanel.add(previewCard)
        contentPanel.add(Box.createVerticalGlue())
        
        val scrollPane = JBScrollPane(contentPanel)
        scrollPane.border = BorderFactory.createEmptyBorder()
        panel.add(scrollPane, BorderLayout.CENTER)
        
        return panel
    }
    
    /**
     * 创建功能卡片
     */
    private fun createFunctionCard(title: String, description: String, buttons: List<Pair<String, () -> Unit>>): JPanel {
        val card = JPanel(BorderLayout())
        card.background = JBColor.background()
        card.border = JBUI.Borders.compound(
            JBUI.Borders.customLine(JBColor.border(), 1),
            JBUI.Borders.empty(20, 25)
        )
        
        // 卡片头部
        val headerPanel = JPanel()
        headerPanel.layout = BoxLayout(headerPanel, BoxLayout.Y_AXIS)
        headerPanel.background = JBColor.background()
        headerPanel.border = JBUI.Borders.empty(0, 0, 15, 0)
        
        val titleLabel = JBLabel(title)
        titleLabel.font = titleLabel.font.deriveFont(Font.BOLD, 18f)
        titleLabel.foreground = JBColor.foreground()
        titleLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val descLabel = JBLabel(description)
        descLabel.font = descLabel.font.deriveFont(13f)
        descLabel.foreground = JBColor.GRAY
        descLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        headerPanel.add(titleLabel)
        headerPanel.add(Box.createVerticalStrut(8))
        headerPanel.add(descLabel)
        
        // 按钮面板
        val buttonPanel = JPanel(GridLayout(1, buttons.size, 12, 0))
        buttonPanel.background = JBColor.background()
        
        buttons.forEach { (buttonText, action) ->
            val button = JButton(buttonText)
            button.preferredSize = Dimension(150, 36)
            button.addActionListener { action() }
            buttonPanel.add(button)
        }
        
        card.add(headerPanel, BorderLayout.NORTH)
        card.add(buttonPanel, BorderLayout.CENTER)
        
        return card
    }

    /**
     * 创建数据预览卡片
     */
    private fun createDataPreviewCard(): JPanel {
        val card = JPanel(BorderLayout())
        card.background = JBColor.background()
        card.border = JBUI.Borders.compound(
            JBUI.Borders.customLine(JBColor.border(), 1),
            JBUI.Borders.empty(20, 25)
        )
        
        // 卡片头部
        val headerPanel = JPanel()
        headerPanel.layout = BoxLayout(headerPanel, BoxLayout.Y_AXIS)
        headerPanel.background = JBColor.background()
        headerPanel.border = JBUI.Borders.empty(0, 0, 15, 0)
        
        val titleLabel = JBLabel("数据预览")
        titleLabel.font = titleLabel.font.deriveFont(Font.BOLD, 18f)
        titleLabel.foreground = JBColor.foreground()
        titleLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val descLabel = JBLabel("当前编程统计概览，实时展示您的代码成就")
        descLabel.font = descLabel.font.deriveFont(13f)
        descLabel.foreground = JBColor.GRAY
        descLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        headerPanel.add(titleLabel)
        headerPanel.add(Box.createVerticalStrut(8))
        headerPanel.add(descLabel)
        
        // 数据内容
        val codeStatsService = CodeStatsService.getInstance(project)
        val aggregated = codeStatsService.getAggregatedStats()
        val unlockedCount = codeStatsService.getUnlockedAchievements().size
        val totalCount = AchievementType.values().size
        
        val dataGrid = JPanel(GridLayout(2, 3, 15, 12))
        dataGrid.background = JBColor.background()
        
        val todayAddedCard = createStatCard("今日新增", "${aggregated.todayAdded} 行", JBColor(Color(76, 175, 80), Color(56, 142, 60)))
        val todayDeletedCard = createStatCard("今日删除", "${aggregated.todayDeleted} 行", JBColor(Color(244, 67, 54), Color(211, 47, 47)))
        val totalCodeCard = createStatCard("累计代码", "${aggregated.totalAdded} 行", JBColor(Color(33, 150, 243), Color(25, 118, 210)))
        val achievementsCard = createStatCard("解锁成就", "$unlockedCount / $totalCount", JBColor(Color(255, 193, 7), Color(255, 160, 0)))
        val streakCard = createStatCard("连续天数", "${codeStatsService.getConsecutiveDays()} 天", JBColor(Color(156, 39, 176), Color(123, 31, 162)))
        val completionRate = if (totalCount > 0) ((unlockedCount.toFloat() / totalCount) * 100).toInt() else 0
        val completionCard = createStatCard("完成度", "$completionRate%", JBColor(Color(96, 125, 139), Color(69, 90, 100)))
        
        dataGrid.add(todayAddedCard)
        dataGrid.add(todayDeletedCard)
        dataGrid.add(totalCodeCard)
        dataGrid.add(achievementsCard)
        dataGrid.add(streakCard)
        dataGrid.add(completionCard)
        
        card.add(headerPanel, BorderLayout.NORTH)
        card.add(dataGrid, BorderLayout.CENTER)
        
        return card
    }

    /**
     * 创建统计数据小卡片
     */
    private fun createStatCard(title: String, value: String, accentColor: JBColor): JPanel {
        val card = JPanel(BorderLayout())
        card.background = JBColor(Color(249, 249, 249), Color(60, 63, 65))
        card.border = JBUI.Borders.compound(
            JBUI.Borders.customLine(JBColor(Color(235, 235, 235), Color(80, 80, 80)), 1),
            JBUI.Borders.empty(12, 15)
        )
        card.preferredSize = Dimension(160, 70)
        
        // 左侧：彩色指示条
        val indicator = JPanel()
        indicator.background = accentColor
        indicator.preferredSize = Dimension(4, 70)
        
        // 内容面板
        val contentPanel = JPanel()
        contentPanel.layout = BoxLayout(contentPanel, BoxLayout.Y_AXIS)
        contentPanel.background = card.background
        contentPanel.border = JBUI.Borders.empty(0, 12, 0, 0)
        
        val titleLabel = JBLabel(title)
        titleLabel.font = titleLabel.font.deriveFont(12f)
        titleLabel.foreground = JBColor.GRAY
        titleLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        val valueLabel = JBLabel(value)
        valueLabel.font = valueLabel.font.deriveFont(Font.BOLD, 16f)
        valueLabel.foreground = JBColor.foreground()
        valueLabel.alignmentX = Component.LEFT_ALIGNMENT
        
        contentPanel.add(titleLabel)
        contentPanel.add(Box.createVerticalStrut(4))
        contentPanel.add(valueLabel)
        contentPanel.add(Box.createVerticalGlue())
        
        card.add(indicator, BorderLayout.WEST)
        card.add(contentPanel, BorderLayout.CENTER)
        
        return card
    }

} 